layui.use(['layer', 'element', 'form', 'upload', 'table', 'jquery'], function () {
    var $ = layui.jquery,
        element = layui.element,
        form = layui.form,
        upload = layui.upload,
        table = layui.table;

    form.render();

    // 搜索
    $(".btn-search-form").click(function () {
        var keywords = $("input[name=keywords]").val();
        $.post('index.php?route=Chess/index&iActId=1001', {keywords: keywords}, function (res) {
            if (res.status == "error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                if (res.data.length > 0) {
                    var html = '';
                    $.each(res.data, function (i, val) {  //遍历二维数组
                        html += '<li class="chess-item" data-chessid="' + val.chessId + '"><img src="https://game.gtimg.cn/images/lol/act/img/tft/champions/' + val.name + '" alt=""><p>' + val.displayName + '</p></li>'
                    });
                    $("#chess-list").html(html);
                    $("#chess-list").find(".chess-item").first().trigger('click');
                }
                return;
            }
        });
        return;
    });

    //渲染种族
    var raceIds = [];

    // CONF.races
    function renderRace(key, is) {
        //添加
        if (is) {
            if ($.inArray(key, raceIds) != -1) {
                return;
            }
            raceIds.push(key);

            $("#race-list").append('<a class="item_' + key + '">||' + CONF.races[key] + '</a>');
        } else {
            //删除
            var pos = $.inArray(key, raceIds);
            if (pos != -1) {
                raceIds.splice(pos, 1);

            }
            $("#race-list").find(".item_" + key).remove();
        }
        $("#chess-form").find("[name='raceIds']").val(raceIds.join(','));
    }

    //渲染职业
    var jobIds = [];

    function renderJob(key, is) {
        //添加
        if (is) {
            if ($.inArray(key, jobIds) != -1) {
                return;
            }
            jobIds.push(key);

            $("#job-list").append('<a class="item_' + key + '">||' + CONF.jobs[key] + '</a>');
        } else {
            //删除
            var pos = $.inArray(key, jobIds);
            if (pos != -1) {
                jobIds.splice(pos, 1);

            }
            $("#job-list").find(".item_" + key).remove();
        }

        $("#chess-form").find("[name='jobIds']").val(jobIds.join(','));
    }

    // 选中的 协同数组
    var TFTIDs = [];
    var SynergiesListArr = [];

    // 渲染协同数组
    function renderSynergies(val, is) {
        if (is) {
            if ($.inArray(val, TFTIDs) != -1) {
                return;
            }
            TFTIDs.push(val);
            $("#synergies-div").append('<img src="' + CONF.TFTIDs[val] + '" class="layui-upload-img item_' + val + '">');
        } else {
            //删除
            var pos = $.inArray(val, TFTIDs);
            if (pos != -1) {
                TFTIDs.splice(pos, 1);
            }
            $("#synergies-div").find(".item_" + val).remove();
        }
        $("#chess-form").find("[name='synergies']").val(TFTIDs.join(','));
    }


    //点击棋子头像
    $("#chess-list").on('click', '.chess-item', function () {
        var that = this;
        var data = {chessId: $(this).data('chessid')};
        $.post('/index.php?route=Chess/getChessInfo&iActId=1001', data, function (res) {
            if (res.status == "error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                $(that).siblings().removeClass('active');
                $(that).addClass('active');

                /*$("#chess-form").find('input').attr('disabled', true);
                $("#chess-form").find('select').attr('disabled', true);
                $("#chess-form").find('textarea').attr('disabled', true);
                $("#chess-form").find('.action-to-update').show();
                $("#chess-form").find('.action-to-submit').hide();*/

                var data = res.data;

                //TFTID
                $("#chess-form").find("[name='TFTID']").val(data.TFTID);
                //棋子id
                $("#chess-form").find("[name='chessId']").val(data.chessId);
                $("#chess-form").find("[name='chessIdShow']").text(data.chessId);
                //棋子名称和称号
                $("#chess-form").find("[name='displayName']").val(data.displayName);
                $("#chess-form").find("[name='name']").val(data.name);
                $("#chess-form").find("[name='title']").val(data.title);

                //费用
                $("#chess-form").find("[name='price']").val(data.price);
                //生命值
                $("#chess-form").find("[name='life']").val(data.life);
                $("#chess-form").find("[name='lifeMag']").val(data.lifeMag);
                $("#show-life").text(data.life + '/' + Math.round(data.life * data.lifeMag * 100) / 100 + '/' + Math.round(data.life * data.lifeMag * data.lifeMag * 100) / 100);

                //法力和护甲
                $("#chess-form").find("[name='magic']").val(data.magic);
                $("#chess-form").find("[name='armor']").val(data.armor);

                //抗魔
                $("#chess-form").find("[name='spellBlock']").val(data.spellBlock);
                //


                //攻击
                $("#chess-form").find("[name='attack']").val(data.attack);
                $("#chess-form").find("[name='attackSpeed']").val(data.attackSpeed);
                $("#chess-form").find("[name='attackRange']").val(data.attackRange);
                $("#chess-form").find("[name='crit']").val(data.crit);
                $("#chess-form").find("[name='attackMag']").val(data.attackMag);
                $("#show-attack").text(data.attack + '/' + Math.round(data.attack * data.attackMag * 100) / 100 + '/' + Math.round(data.attack * data.attackMag * data.attackMag * 100 / 100))
                //种族和职业

                raceIds = data.raceIds.split(',');
                $("#race-list").html('');
                raceIds.forEach(function (key) {
                    $("#race-list").append('<a class="item_' + key + '">||' + CONF.races[key] + '</a>');
                });
                $("#chess-form").find("[name='raceIds']").val(data.raceIds);

                jobIds = data.jobIds.split(',');
                $("#job-list").html('');
                jobIds.forEach(function (key) {
                    $("#job-list").append('<a class="item_' + key + '">||' + CONF.jobs[key] + '</a>');
                });
                $("#chess-form").find("[name='jobIds']").val(data.jobIds);


                // 协同
                if (data.synergies == '') {
                    TFTIDs = [];
                } else {
                    TFTIDs = data.synergies.split(',');
                }
                $("#synergies-div").html('');
                TFTIDs.forEach(function (key) {
                    $("#synergies-div").append('<img src="' + CONF.TFTIDs[key] + '" class="layui-upload-img item_' + key + '">');
                });


                $("#chess-form").find("[name='synergies']").val(data.synergies);
                //技能
                $("#chess-form").find("[name='skillName']").val(data.skillName);
                $("#chess-form").find("[name='skillType']").val(data.skillType);
                $("#chess-form").find("[name='skillIntroduce']").val(data.skillIntroduce);
                $("#chess-form").find("[name='skillImage']").val(data.skillImage);
                $("#chess-form").find("[name='skillDetail']").val(data.skillDetail);
                $("#chess-form").find("[name='originalImage']").val(data.originalImage);
                $("#image-path").attr('src', data.skillImage);

                $("#chess-form").find("[name='illustrate']").val(data.illustrate);

                var originalImage = data.originalImage.split(",");
                var imgs = '';

                $.each(originalImage, function (k, v) {
                    imgs += '<div class="originalImageDiv"><span class="delete">&times;</span>';
                    imgs += '<img  src="' + v + '">';
                    imgs += '</div>';
                })
                $("#original-image-path").html(imgs);

                $(that).find('img').attr('src', 'https://game.gtimg.cn/images/lol/act/img/tft/champions/' + data.name);

                form.render();


            }

        })
    });

    $("#chess-form").on('input', "[name='attackMag'],[name='attack']", function () {
        var attack = $("#chess-form").find("[name='attack']").val();
        var attackMag = $("#chess-form").find("[name='attackMag']").val();
        $("#show-attack").text(attack + '/' + Math.round(attack * attackMag * 100) / 100 + '/' + Math.round(attack * attackMag * attackMag * 100) / 100);

    });
    $("#chess-form").on('input', "[name='lifeMag'],[name='life']", function () {
        var life = $("#chess-form").find("[name='life']").val();
        var lifeMag = $("#chess-form").find("[name='lifeMag']").val();
        $("#show-life").text(life + '/' + Math.round(life * lifeMag * 100) / 100 + '/' + Math.round(life * lifeMag * lifeMag * 100) / 100);

    })


    $("#chess-list").find(".chess-item").first().trigger('click');

    //点击删除
    $("#chess-form").on('click', '.action-to-delete', function () {
        layer.confirm('是否要删除该数据？', {icon: 3, title: '提示'}, function (index) {
            var dataType = 4;
            var id = $('#chess-form').find("input[name=chessId]").val()
            layer.close(index);
            var url = "/index.php?route=Main/deleteData&iActId=1001";
            $.ajax({
                url: url, type: "post", dataType: "json",
                data: {dataType: dataType, id: id},
                beforeSend: function () {
                    this.layerIndex = layer.load(0, {shade: [0.5, '#393D49']});
                },
                success: function (data) {
                    if (data.status == "error") {
                        layer.msg(data.msg);//失败的表情
                        return;
                    } else if (data.status == "success") {
                        layer.msg(data.msg, {
                            icon: 1,//成功的表情
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            parent.$(".refresh").click();
                        });
                    }
                },
                complete: function () {
                    layer.close(this.layerIndex);
                },
            });
        });
    });


    //点击编辑
    /*$("#chess-form").on('click', '.action-to-update', function () {
        $("#chess-form").find('input').removeAttr('disabled');
        $("#chess-form").find('select').removeAttr('disabled');
        $("#chess-form").find('textarea').removeAttr('disabled');

        $("#chess-form").find('.action-to-update').hide();
        $("#chess-form").find('.action-to-submit').show();
        is_update = true;
        form.render();

    });*/
    //点击保存

    $("#chess-form").on('click', '.action-to-submit', function () {
        var price = $("input[name=price]").val();
        if (isNaN(price) || price == '') {
            layer.msg('棋子费用必须为数字类型');
            return;
        }
        var spellBlock = $("input[name=spellBlock]").val();
        if (isNaN(spellBlock) || spellBlock == '') {
            layer.msg('魔抗必须为数字类型');
            return;
        }
        var attackSpeed = $("input[name=attackSpeed]").val();
        if (isNaN(attackSpeed) || attackSpeed == '') {
            layer.msg('攻击速度必须为数字类型');
            return;
        }
        var magic = $("input[name=magic]").val();
        if (isNaN(magic) || magic == '') {
            layer.msg('法力必须为数字类型');
            return;
        }
        var attackRange = $("input[name=attackRange]").val();
        if (isNaN(attackRange) || attackRange == '') {
            layer.msg('攻击范围必须为数字类型');
            return;
        }
        var crit = $("input[name=crit]").val();
        if (isNaN(crit) || crit == '') {
            layer.msg('暴击率必须为数字类型');
            return;
        }
        var armor = $("input[name=armor]").val();
        if (isNaN(armor) || armor == '') {
            layer.msg('护甲必须为数字类型');
            return;
        }
        var attackMag = $("input[name=attackMag]").val();
        if (isNaN(attackMag) || attackMag == '') {
            layer.msg('攻击力系数必须为数字类型');
            return;
        }
        var attack = $("input[name=attack]").val();
        if (isNaN(attack) || attack == '') {
            layer.msg('初始攻击力必须为数字类型');
            return;
        }
        var life = $("input[name=life]").val();
        if (isNaN(life) || life == '') {
            layer.msg('初始生命值必须为数字类型');
            return;
        }
        var lifeMag = $("input[name=lifeMag]").val();
        if (isNaN(lifeMag) || lifeMag == '') {
            layer.msg('生命值系数必须为数字类型');
            return;
        }
        if ($("input[name=originalImage]").val() == '') {
            layer.msg('请上传原图');
            return false;
        }

        var data = $('#chess-form').serialize();

        $.post('/index.php?route=chess/update&iActId=1001', data, function (res) {
            if (res.status == "error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                /*$("#chess-form").find('input').attr('disabled', true);
                $("#chess-form").find('select').attr('disabled', true);
                $("#chess-form").find('textarea').attr('disabled', true);
                $("#chess-form").find('.action-to-update').show();
                $("#chess-form").find('.action-to-submit').hide();
                is_update = false;*/
                form.render();

                layer.msg('编辑成功');
                $('.chess-item.active').trigger('click');
            }
        });
    });


    //更换图标

    upload.render({
        elem: '#image' //绑定元素
        , url: '/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
        , accept: 'images'
        , data: {id: 1, type: 'skill'}
        , done: function (res) {
            $("#chess-form").find("[name='skillImage']").val(res.imagePath);
            $("#image-path").attr('src', res.imagePath);
            //上传完毕回调
        }
        , error: function () {
            //请求异常回调
        }
    });

    upload.render({
        elem: '#original-image' //绑定元素
        , url: '/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
        , accept: 'images'
        , data: {id: 1, type: 'original-image'}
        , done: function (res) {

            var originalImage = $("#chess-form").find("[name='originalImage']").val();
            if (!originalImage) {
                originalImage = [];
            } else {
                originalImage = originalImage.split(",");
            }

            originalImage.push(res.imagePath)

            var imgs = '';

            $.each(originalImage, function (k, v) {
                imgs += '<div class="originalImageDiv"><span class="delete">&times;</span>';
                imgs += '<img  src="' + v + '">';
                imgs += '</div>';
            })
            $("#original-image-path").html(imgs);

            if (originalImage.length > 1) {
                $("#chess-form").find("[name='originalImage']").val(originalImage.join(','));
            } else {
                $("#chess-form").find("[name='originalImage']").val(originalImage[0]);
            }


            //上传完毕回调
        }
        , error: function () {
            //请求异常回调
        }
    });

    //删除原图中的图片

    $("#original-image-path").on('click', '.delete', function () {

        if (!is_update) {
            return;
        }
        layer.confirm('是否要删除该数据？', {icon: 3, title: '提示'}, function (index) {
            layer.close(index);
            var delImg = $(this).attr('src');
            var originalImage = $("#chess-form").find("[name='originalImage']").val();
            if (!originalImage) {
                originalImage = [];
            } else {
                originalImage = originalImage.split(",");
            }

            originalImage.splice($.inArray(delImg, originalImage), 1)
            var imgs = '';

            $.each(originalImage, function (k, v) {
                imgs += '<div class="originalImageDiv"><span class="delete">&times;</span>';
                imgs += '<img  src="' + v + '">';
                imgs += '</div>';
            })
            $("#original-image-path").html(imgs);

            if (originalImage.length > 1) {
                $("#chess-form").find("[name='originalImage']").val(originalImage.join(','));
            } else {
                $("#chess-form").find("[name='originalImage']").val(originalImage[0]);
            }
        });

    });


    //选择种族
    $("#select-race").click(function () {

        if (!is_update) {
            return;
        }
        var checkbox = ''
        $.each(CONF.races, function (key, name) {
            //选中
            var checked = '';
            if ($.inArray(key, raceIds) != -1) {
                checked = 'checked';
            }
            checkbox += '<input ' + checked + ' type="checkbox" name="race[]" value="' + key + '" title="' + name + '"  >';
        })

        layer.open({
            type: 1,
            content: '<form id="race-list" class="layui-form">' + checkbox + '</form>',
            btn: ['确定'],
            offset: 't'
        })
        form.render('checkbox');
    });

    //选择职业
    $("#select-job").click(function () {
        if (!is_update) {
            return;
        }
        var checkbox = ''
        $.each(CONF.jobs, function (key, name) {
            //选中
            var checked = '';
            if ($.inArray(key, jobIds) != -1) {
                checked = 'checked';
            }
            checkbox += '<input ' + checked + ' type="checkbox" name="job[]" value="' + key + '" title="' + name + '"  >';
        })

        layer.open({
            type: 1,
            content: '<form id="job-list" class="layui-form">' + checkbox + '</form>',
            btn: ['确定'],
            offset: 't'
        });
        form.render('checkbox');
    });

    //
    form.on('checkbox', function (data) {
        var name = $(data.elem).attr('name');
        var is = data.elem.checked;
        var value = data.value;

        if (name == 'race[]') {
            renderRace(value, is);
        } else if (name == 'checkbox') {
            renderSynergies(value, is);
        } else {
            renderJob(value, is);
        }
    });

    // 添加
    $(".chess-add").on('click', function () {
        var index = layer.open({
            title: '添加',
            type: 2,
            content: '/index.php?route=Chess/add&iActId=1001'
        });
        layer.full(index);
    });

    form.on('submit(chess-add)', function (data) {
        var price = $("input[name=price]").val();
        if (isNaN(price) || price == '') {
            layer.msg('棋子费用必须为数字类型');
            return;
        }
        var spellBlock = $("input[name=spellBlock]").val();
        if (isNaN(spellBlock) || spellBlock == '') {
            layer.msg('魔抗必须为数字类型');
            return;
        }
        var attackSpeed = $("input[name=attackSpeed]").val();
        if (isNaN(attackSpeed) || attackSpeed == '') {
            layer.msg('攻击速度必须为数字类型');
            return;
        }
        var magic = $("input[name=magic]").val();
        if (isNaN(magic) || magic == '') {
            layer.msg('法力必须为数字类型');
            return;
        }
        var attackRange = $("input[name=attackRange]").val();
        if (isNaN(attackRange) || attackRange == '') {
            layer.msg('攻击范围必须为数字类型');
            return;
        }
        var crit = $("input[name=crit]").val();
        if (isNaN(crit) || crit == '') {
            layer.msg('暴击率必须为数字类型');
            return;
        }
        var armor = $("input[name=armor]").val();
        if (isNaN(armor) || armor == '') {
            layer.msg('护甲必须为数字类型');
            return;
        }
        var attackMag = $("input[name=attackMag]").val();
        if (isNaN(attackMag) || attackMag == '') {
            layer.msg('攻击力系数必须为数字类型');
            return;
        }
        var attack = $("input[name=attack]").val();
        if (isNaN(attack) || attack == '') {
            layer.msg('初始攻击力必须为数字类型');
            return;
        }
        var life = $("input[name=life]").val();
        if (isNaN(life) || life == '') {
            layer.msg('初始生命值必须为数字类型');
            return;
        }
        var lifeMag = $("input[name=lifeMag]").val();
        if (isNaN(lifeMag) || lifeMag == '') {
            layer.msg('生命值系数必须为数字类型');
            return;
        }
        if ($("input[name=raceIds]").val() == '') {
            layer.msg('请选择种族');
            return false;
        }
        if ($("input[name=jobIds]").val() == '') {
            layer.msg('请选择职业');
            return false;
        }
        if ($("input[name=skillImage]").val() == '') {
            layer.msg('请上传图标');
            return false;
        }
        if ($("input[name=originalImage]").val() == '') {
            layer.msg('请上传原图');
            return false;
        }
        console.log('field', data.field); //当前容器的全部表单字段，名值对形式：{name: value}
        $.ajax({
            url: "/index.php?route=Chess/addSave&iActId=1001",
            type: 'POST',
            dataType: 'JSON',
            data: $("#chess-form").serializeArray(),
            success: function (res) {
                if (res.status == 'success') {
                    window.parent.location.reload();//刷新父页面
                    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                    parent.layer.close(index);
                } else {
                    layer.msg(res.msg);
                    return false;
                }
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    // 全选/反选
    /*form.on('checkbox(SynergiesAllCheckbox)', function (data) {
        if (data.elem.checked == true) {
            $('input[name="checkbox"]').prop("checked", true);
            $.each(SynergiesListArr, function (index, item) {
                $("#synergies-div").append('<img src="' + CONF.TFTIDs[item.TFTID] + '" class="layui-upload-img item_' + item.TFTID + '">');
                TFTIDs.push(item.TFTID);
            });
        } else {
            $('input[name="checkbox"]').prop("checked", false);
            $.each(SynergiesListArr, function (index, item) {

                var pos = $.inArray(item.TFTID, TFTIDs);
                if (pos != -1) {
                    TFTIDs.splice(pos, 1);
                }
                $("#synergies-div").find(".item_" + item.TFTID).remove();

            });
        }
        form.render('checkbox');
        $("#chess-form").find("[name='synergies']").val(TFTIDs.join(','));
    });*/

    // 选择协同
    $(".synergies-click").on('click', function () {
        if (!is_update) {
            return;
        }
        var chessid = $("#chess-list .active").data("chessid");
        var index = layer.load(1, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
        $.post('/index.php?route=Chess/getSynergiesList&iActId=1001', {chessId: chessid}, function (res) {
            if (res.status == 'success') {
                var html = '';
                SynergiesListArr = res.data.SynergiesList;
                $.each(res.data.SynergiesList, function (index, item) {

                    if ($.inArray(item.TFTID, TFTIDs) != -1) {
                        html += '<tr><td><input  type="checkbox" name="checkbox" value="' + item.TFTID + '" checked></td>';
                    } else {
                        html += '<tr><td><input  type="checkbox" name="checkbox" value="' + item.TFTID + '"></td>';
                    }


                    var jobNames = "";
                    for (i = 0; i < item.jobIds.length; i++) {
                        jobNames += CONF.jobs[item.jobIds[i]] + "/";
                    }
                    html += '<td title="' + jobNames.slice(0, jobNames.length - 1) + '">' + jobNames.slice(0, jobNames.length - 1) + '</td>';

                    var raceNames = "";
                    for (i = 0; i < item.raceIds.length; i++) {
                        raceNames += CONF.races[item.raceIds[i]] + "/";
                    }

                    html += '<td title="' + raceNames.slice(0, raceNames.length - 1) + '">' + raceNames.slice(0, raceNames.length - 1) + '</td>';
                    html += ' <td title="' + item.displayName + '">' + item.displayName + '</td></tr>'
                });

                $("#synergies-list").html(html);
                layer.close(index);

                layer.open({
                    type: 1,
                    btn: ['确定'],
                    skin: 'layui-layer-rim', //加上边框
                    area: ['500px', '500px'], //宽高
                    content: $("#synergies-form"),
                    end: function (res) {
                        $("#synergies-form").hide();
                    }
                });
                form.render();

            }
        })
    });

    // 监听表单输入时间
    $("#synergies-form").on("input propertychange", '.synergies-input', function (e) {
        //获取input输入的值
        var val = $(this).val().trim();
        $.each($("#synergies-list tr"), function (index, item) {
            if (val == '') {
                $(item).show();
            } else {
                var job = $(item).children('td').eq(1).text();
                var race = $(item).children('td').eq(2).text();
                var displayName = $(item).children('td').eq(3).text();
                if (displayName.indexOf(val) == -1 && job.indexOf(val) == -1 && race.indexOf(val) == -1) {
                    $(item).hide();
                } else {
                    $(item).show();
                }
            }
        });
    });


})





